package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceRepository;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseRepository;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class DeviceManagementService {
    private final DeviceRepository deviceRepository;
    private final GreenhouseRepository greenhouseRepository;

    @Transactional
    public Device createDevice(Device device) {
        device.setCreateTime(DateUtils.toDate(LocalDateTime.now()));
        return deviceRepository.save(device);
    }

    @Transactional
    public Device bindDeviceToGreenhouse(Long deviceId, Long greenhouseId) {
        Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new EntityNotFoundException("Device not found with id: " + deviceId));
        
        Greenhouse greenhouse = greenhouseRepository.findById(greenhouseId)
                .orElseThrow(() -> new EntityNotFoundException("Greenhouse not found with id: " + greenhouseId));

        // 检查大棚是否已经绑定了同类型的设备
        if (deviceRepository.existsByDeviceTypeAndGreenhouseId(device.getDeviceType(), greenhouseId)) {
            throw new IllegalStateException("Greenhouse already has a device of this type");
        }

        device.setGreenhouse(greenhouse);
        return deviceRepository.save(device);
    }

    public List<Device> getAllDevices() {
        return deviceRepository.findAll();
    }

    public Device getDeviceBySerialNumber(String serialNumber) {
        return deviceRepository.findBySerialNumber(serialNumber)
                .orElseThrow(() -> new EntityNotFoundException("Device not found with serial number: " + serialNumber));
    }

    @Transactional
    public void deleteDevice(Long deviceId) {
        deviceRepository.deleteById(deviceId);
    }
} 